package d7;

import com.jieshen.TreeNode;
import com.jieshen.utils.BinaryTree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class offer28 {
    /**
     * 把每一行的节点，抽取出来成一个列表，接着就只需要判断这个列表是否对称了。
     *
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if (root == null)
            return true;
        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> level;
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            if (size % 2 != 0 && size > 1)
                return false;
            level = new ArrayList<>();
            //把这一层的节点全提取出来
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.remove();
                if (node.left != null)
                    level.add(node.left.val);
                else
                    level.add(null);
                if (node.right != null)
                    level.add(node.right.val);
                else
                    level.add(null);

                if (node.left != null)
                    queue.add(node.left);
                if (node.right != null)
                    queue.add(node.right);
            }
            int level_size = level.size();
            for (int i = 0; i < level_size / 2; i++) {
                if (level.get(i) != level.get(level_size - 1 - i))
                    return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Integer[] arr = {1,2,2,3,4,4,3};
        TreeNode root = new BinaryTree().BuildTree(arr);
        boolean symmetric = new offer28().isSymmetric(root);
        System.out.println(symmetric);
    }
}
